<template>
  <div class="promotion-edit">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑活动' : '创建活动' }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="promotion-form"
      >
        <!-- 基本信息 -->
        <el-divider>基本信息</el-divider>
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>

        <el-form-item label="活动类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择活动类型">
            <el-option
              v-for="type in promotionTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :disabled-date="disabledDate"
            :disabled-time="disabledTime"
          />
        </el-form-item>

        <!-- 活动规则 -->
        <el-divider>活动规则</el-divider>
        <template v-if="form.type === 'discount'">
          <el-form-item label="满减规则" prop="rules">
            <div class="rule-list">
              <div
                v-for="(rule, index) in form.rules"
                :key="index"
                class="rule-item"
              >
                <el-input-number
                  v-model="rule.threshold"
                  :min="0"
                  :precision="2"
                  placeholder="满"
                />
                <span class="rule-separator">减</span>
                <el-input-number
                  v-model="rule.discount"
                  :min="0"
                  :precision="2"
                  placeholder="减"
                />
                <el-button
                  type="danger"
                  link
                  @click="handleRemoveRule(index)"
                >
                  删除
                </el-button>
              </div>
              <el-button type="primary" link @click="handleAddRule">
                添加规则
              </el-button>
            </div>
          </el-form-item>
        </template>

        <template v-else-if="form.type === 'seckill'">
          <el-form-item label="秒杀时段" prop="timeSlots">
            <div class="time-slot-list">
              <div
                v-for="(slot, index) in form.timeSlots"
                :key="index"
                class="time-slot-item"
              >
                <el-time-picker
                  v-model="slot.startTime"
                  placeholder="开始时间"
                  format="HH:mm"
                />
                <span class="slot-separator">至</span>
                <el-time-picker
                  v-model="slot.endTime"
                  placeholder="结束时间"
                  format="HH:mm"
                />
                <el-button
                  type="danger"
                  link
                  @click="handleRemoveTimeSlot(index)"
                >
                  删除
                </el-button>
              </div>
              <el-button type="primary" link @click="handleAddTimeSlot">
                添加时段
              </el-button>
            </div>
          </el-form-item>
        </template>

        <template v-else-if="form.type === 'group'">
          <el-form-item label="拼团人数" prop="groupSize">
            <el-input-number
              v-model="form.groupSize"
              :min="2"
              :max="10"
              placeholder="请输入拼团人数"
            />
          </el-form-item>
          <el-form-item label="拼团时限" prop="groupTimeLimit">
            <el-input-number
              v-model="form.groupTimeLimit"
              :min="1"
              :max="72"
              placeholder="请输入拼团时限（小时）"
            />
          </el-form-item>
        </template>

        <template v-else-if="form.type === 'new_user'">
          <el-form-item label="新人专享价" prop="newUserDiscount">
            <el-input-number
              v-model="form.newUserDiscount"
              :min="0"
              :max="10"
              :precision="1"
              :step="0.1"
              placeholder="请输入折扣率"
            />
            <span class="form-tip">折</span>
          </el-form-item>
        </template>

        <!-- 商品选择 -->
        <el-divider>商品选择</el-divider>
        <el-form-item label="选择商品" prop="products">
          <div class="product-selection">
            <el-button type="primary" @click="handleSelectProducts">
              选择商品
            </el-button>
            <el-table
              v-if="form.products.length > 0"
              :data="form.products"
              border
              style="width: 100%; margin-top: 20px"
            >
              <el-table-column prop="name" label="商品名称" min-width="200" />
              <el-table-column prop="price" label="原价" width="120">
                <template #default="{ row }">
                  ¥{{ row.price }}
                </template>
              </el-table-column>
              <el-table-column label="活动价" width="200">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.promotionPrice"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    :max="row.price"
                  />
                </template>
              </el-table-column>
              <el-table-column label="库存" width="120">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.stock"
                    :min="0"
                    :max="row.totalStock"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    link
                    @click="handleRemoveProduct($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品选择对话框 -->
    <el-dialog
      v-model="productDialog.visible"
      title="选择商品"
      width="800px"
      append-to-body
    >
      <div class="product-dialog-content">
        <div class="search-bar">
          <el-input
            v-model="productDialog.keyword"
            placeholder="请输入商品名称搜索"
            clearable
            @keyup.enter="handleSearchProducts"
          >
            <template #append>
              <el-button @click="handleSearchProducts">搜索</el-button>
            </template>
          </el-input>
        </div>

        <el-table
          :data="productDialog.list"
          border
          style="width: 100%"
          @selection-change="handleProductSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="商品名称" min-width="200" />
          <el-table-column prop="price" label="原价" width="120">
            <template #default="{ row }">
              ¥{{ row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="stock" label="库存" width="100" />
          <el-table-column prop="sales" label="销量" width="100" />
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="productDialog.page.current"
            v-model:page-size="productDialog.page.size"
            :total="productDialog.page.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleProductPageSizeChange"
            @current-change="handleProductPageChange"
          />
        </div>
      </div>

      <template #footer>
        <el-button @click="productDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmProducts">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import {
  getMerchantPromotionDetail,
  createMerchantPromotion,
  updateMerchantPromotion,
  getMerchantProducts
} from '@/api/merchant'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 活动类型选项
const promotionTypes = [
  { label: '满减活动', value: 'discount' },
  { label: '秒杀活动', value: 'seckill' },
  { label: '拼团活动', value: 'group' },
  { label: '新人专享', value: 'new_user' }
]

// 表单数据
const form = reactive({
  name: '',
  type: '',
  timeRange: [],
  rules: [],
  timeSlots: [],
  groupSize: 2,
  groupTimeLimit: 24,
  newUserDiscount: 8.5,
  products: []
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  timeRange: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  rules: [
    {
      required: true,
      message: '请添加满减规则',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.type === 'discount' && (!value || value.length === 0)) {
          callback(new Error('请添加满减规则'))
        } else {
          callback()
        }
      }
    }
  ],
  timeSlots: [
    {
      required: true,
      message: '请添加秒杀时段',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (form.type === 'seckill' && (!value || value.length === 0)) {
          callback(new Error('请添加秒杀时段'))
        } else {
          callback()
        }
      }
    }
  ],
  groupSize: [
    {
      required: true,
      message: '请输入拼团人数',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (form.type === 'group' && !value) {
          callback(new Error('请输入拼团人数'))
        } else {
          callback()
        }
      }
    }
  ],
  groupTimeLimit: [
    {
      required: true,
      message: '请输入拼团时限',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (form.type === 'group' && !value) {
          callback(new Error('请输入拼团时限'))
        } else {
          callback()
        }
      }
    }
  ],
  newUserDiscount: [
    {
      required: true,
      message: '请输入新人专享折扣',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (form.type === 'new_user' && !value) {
          callback(new Error('请输入新人专享折扣'))
        } else {
          callback()
        }
      }
    }
  ],
  products: [
    {
      required: true,
      message: '请选择活动商品',
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择活动商品'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 商品选择对话框
const productDialog = reactive({
  visible: false,
  keyword: '',
  list: [],
  selected: [],
  page: {
    current: 1,
    size: 10,
    total: 0
  }
})

// 禁用日期
const disabledDate = (time) => {
  return dayjs(time).isBefore(dayjs(), 'day')
}

// 禁用时间
const disabledTime = (date, type) => {
  if (type === 'start') {
    const now = dayjs()
    if (dayjs(date).isSame(now, 'day')) {
      return {
        hours: () => Array.from({ length: now.hour() }, (_, i) => i),
        minutes: () => Array.from({ length: now.minute() }, (_, i) => i)
      }
    }
  }
  return {}
}

// 添加满减规则
const handleAddRule = () => {
  form.rules.push({
    threshold: 0,
    discount: 0
  })
}

// 删除满减规则
const handleRemoveRule = (index) => {
  form.rules.splice(index, 1)
}

// 添加秒杀时段
const handleAddTimeSlot = () => {
  form.timeSlots.push({
    startTime: null,
    endTime: null
  })
}

// 删除秒杀时段
const handleRemoveTimeSlot = (index) => {
  form.timeSlots.splice(index, 1)
}

// 选择商品
const handleSelectProducts = () => {
  productDialog.visible = true
  productDialog.keyword = ''
  productDialog.selected = []
  getProductList()
}

// 搜索商品
const handleSearchProducts = () => {
  productDialog.page.current = 1
  getProductList()
}

// 获取商品列表
const getProductList = async () => {
  try {
    const params = {
      page: productDialog.page.current,
      size: productDialog.page.size,
      keyword: productDialog.keyword
    }
    const { data } = await getMerchantProducts(params)
    productDialog.list = data.list
    productDialog.page.total = data.total
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  }
}

// 商品选择变化
const handleProductSelectionChange = (selection) => {
  productDialog.selected = selection
}

// 商品分页
const handleProductPageSizeChange = (val) => {
  productDialog.page.size = val
  getProductList()
}

const handleProductPageChange = (val) => {
  productDialog.page.current = val
  getProductList()
}

// 确认选择商品
const handleConfirmProducts = () => {
  const newProducts = productDialog.selected.map(item => ({
    id: item.id,
    name: item.name,
    price: item.price,
    promotionPrice: item.price,
    stock: item.stock,
    totalStock: item.stock
  }))
  form.products = newProducts
  productDialog.visible = false
}

// 删除商品
const handleRemoveProduct = (index) => {
  form.products.splice(index, 1)
}

// 获取活动详情
const getPromotionDetail = async () => {
  try {
    const { data } = await getMerchantPromotionDetail(route.params.id)
    Object.assign(form, {
      name: data.name,
      type: data.type,
      timeRange: [data.startTime, data.endTime],
      rules: data.rules || [],
      timeSlots: data.timeSlots || [],
      groupSize: data.groupSize,
      groupTimeLimit: data.groupTimeLimit,
      newUserDiscount: data.newUserDiscount,
      products: data.products || []
    })
  } catch (error) {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    const [startTime, endTime] = form.timeRange
    const params = {
      ...form,
      startTime,
      endTime
    }
    delete params.timeRange

    if (isEdit.value) {
      await updateMerchantPromotion(route.params.id, params)
      ElMessage.success('更新成功')
    } else {
      await createMerchantPromotion(params)
      ElMessage.success('创建成功')
    }
    router.push('/merchant/marketing')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('保存活动失败:', error)
      ElMessage.error('保存活动失败')
    }
  }
}

// 取消
const handleCancel = () => {
  router.back()
}

onMounted(() => {
  if (isEdit.value) {
    getPromotionDetail()
  }
})
</script>

<style lang="scss" scoped>
.promotion-edit {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .promotion-form {
    max-width: 800px;
    margin: 0 auto;
  }

  .rule-list,
  .time-slot-list {
    .rule-item,
    .time-slot-item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .rule-separator,
      .slot-separator {
        margin: 0 10px;
      }
    }
  }

  .product-selection {
    .el-table {
      margin-top: 20px;
    }
  }

  .form-tip {
    margin-left: 10px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }

  .product-dialog-content {
    .search-bar {
      margin-bottom: 20px;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 